package com.i72.basic;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jiangj
 * @version 1.0.0
 * @ClassName SOAServiceAddress.java
 * @Description TODO
 * @createTime 2021年12月28日 18:02:00
 */
@Slf4j
@Data
public class SOAServiceAddress {

    private Map<String, List<SOAServiceNode>> nodeListMap = new HashMap<>();

    /**
     * 轮询自增索引号
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 读写锁
     */
    private boolean isChanging = false;

    /**
     * 重置所有服务节点
     */
    void clear() {
        nodeListMap.clear();
    }

    void lock() {
        isChanging = true;
        log.debug("change start");
    }

    void unLock() {
        isChanging = false;
        log.debug("change finish");
    }

    /**
     * 移除某个类型的某个节点
     * @param type 节点类型
     * @param ip 节点ip
     */
    void remove(SOAServiceCenter.NodeType type, String ip) {
        if (nodeListMap.get(type.toString()) != null) {
            nodeListMap.get(type.toString()).remove(new SOAServiceNode(ip, null));
        }
    }

    /**
     * 添加某个类型的某个节点
     * @param type 节点类型
     * @param ip 节点ip
     */
    void add(SOAServiceCenter.NodeType type, String ip) {
        List<SOAServiceNode> soaServiceNodes = nodeListMap.computeIfAbsent(type.toString(), k -> new ArrayList<>());
        soaServiceNodes.add(new SOAServiceNode(ip, (new SOAServiceCenter()).new NodeProperties(type)));
    }

    /**
     * 判断某个类型的某个节点是否存在
     * @param type 节点类型
     * @param ip 节点ip
     */
    boolean exist(SOAServiceCenter.NodeType type, String ip) {
        if (nodeListMap.get(type.toString()) == null) {
            return false;
        }
        return nodeListMap.get(type.toString()).contains(new SOAServiceNode(ip, null));
    }

    /**
     * 判断某个节点类型是否存在
     * @param type 节点类型
     */
    boolean exist(SOAServiceCenter.NodeType type) {
        return nodeListMap.containsKey(type.toString());
    }

    /**
     * 获取指定类型的可用服务节点
     * @param type 节点类型
     */
    String getNode(SOAServiceCenter.NodeType type) {
        waitChangeFinish();
        String ip = null;
        if (nodeListMap.containsKey(type.toString())) {
            List<SOAServiceNode> nodes = nodeListMap.get(type.toString());
            if(nodes!=null && nodes.size()>0){
            //if (!ListHelper.isNullOrEmpty(nodes)) {
                if (nodes.size() == 1) {
                    ip = nodes.get(0).getIp();
                } else {
                    ip = nodes.get(atomicInteger.getAndIncrement() % nodes.size()).getIp();
                }
            }
        }
        log.debug("get SOAServiceNode from type {}: {}", type.toString(), ip);
        return ip;
    }

    void setNodeListMap(Map<String, List<SOAServiceNode>> nodeListMap) {
        if (nodeListMap == null) {
            return;
        }
        this.nodeListMap.putAll(nodeListMap);
    }

    private void waitChangeFinish() {
        int waitTimes = 0;
        while (isChanging) {
            log.debug("wait for change finish");
            try {
                Thread.sleep(5);
            } catch (InterruptedException ignored) {}
            waitTimes++;
            if (waitTimes > 5) {
                isChanging = false;
            }
        }
    }

    @Override
    public String toString() {
        if (nodeListMap.size() == 0) return "";
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : nodeListMap.keySet()) {
            stringBuilder.append(key);
            stringBuilder.append(":");
            for (SOAServiceNode node : nodeListMap.get(key)) {
                stringBuilder.append(node.getIp());
                stringBuilder.append(",");
            }
        }
        return stringBuilder.toString();
    }

}
